<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2018/10/15
 * Time: 16:07
 */

namespace app\index\service;


use app\common\Baidu;
use app\index\model\Comment;
use app\index\model\Vote;
use app\index\model\VoteData;
use app\index\model\VoteItems;
use app\index\model\VoteType;
use app\index\model\VoteWhite;
use think\Db;

class VoteService  extends BaseService
{

    public function __construct()
    {

    }

    /**
     * @param $itemId
     * @param $mobile
     * @param $ip
     * 投票
     */
    public function vote($voteId,$itemId,$mobile,$ip,$deviceId)
    {

        //检测活动是否存在
        $vote = Vote::getVote($voteId);
        if(!$vote)
            return dataReturn(1,'活动不存在');

        //检测该条数据是否存在
        $item = VoteItems::getOneItem($voteId,$itemId);

        if(!$item){
            return dataReturn(1,'数据不存在');
        }

        if(!$vote['enable']){
            return dataReturn(1,'暂时不能投票');
        }

        if(!$item['enable']){
            return dataReturn(1,'该数据暂时不能投票');
        }
        //检测投票规则
        $now = time();
        if($now < $vote['start'] )
            return dataReturn(1,'活动尚未开始');

        if( $now> $vote['end'])
            return dataReturn(1,'活动已结束');

        $userInfo = $this->getLeaveNums($vote,$mobile,$ip,$deviceId,$itemId);
        if($userInfo['leave_nums'] <=0 )
            return dataReturn(2,'您今日的投票数已经用完',$userInfo);
        if($userInfo['this_leave_nums'] !== '' && $userInfo['this_leave_nums'] <= 0)
            return dataReturn(3,'达到上限，请投其他',$userInfo);

        //默认一次投1票
        $nums = 1;
        //如果一次点击投票数1，需计算此次投票数
        if($vote['click_nums']>1){
            //剩余没投的票
            $nums = $userInfo['leave_nums'] > $vote['click_nums'] ? $vote['click_nums'] : $userInfo['leave_nums'];
            if($vote['per_nums'] >0){
                $nums = $userInfo['this_leave_nums'] > $nums ? $nums : $userInfo['this_leave_nums'] ;
            }
        }

        $data = [
            'vote_id' => $voteId,
            'vote_item_id' => $itemId,
            'mid'=>$item['mid'],
            'mobile'=>$mobile,
            'ip'=>$ip,
            'device_id'=>$deviceId,
            'nums'=>$nums,
            'addtime'=>time(),
            'modtime'=>time(),
        ];
        $status = false;
        Db::startTrans();
        try{
            $res1 = VoteData::insert($data);
            $res2 = VoteItems::where('id',$itemId)
                ->inc('real',$nums)
                ->inc('total',$nums)
                ->update();
            if($res1 && $res2){
                Db::commit();
                $userInfo['leave_nums'] -= $nums;
                if($userInfo['this_leave_nums'] !== '')
                    $userInfo['this_leave_nums'] -= $nums;
                $status = true;
            }else{
                Db::rollback();
            }

        }catch (\Exception $e){
            Db::rollback();
        }
        $userInfo['add'] = $nums;
        if($status){
            //投票成功清除缓存
            $this->clearVoteItems($vote['id']);
            return dataReturn(0,'投票成功,您今日还可以投'.$userInfo['leave_nums'].'票',$userInfo);
        }
        return dataReturn(1,'保存失败');

    }

    public function getVote($id)
    {
        $vote = Vote::getVote($id);
        return $vote;
    }

    public function getItems($voteId,$typeId,$order= '',$keyword ='',$mid=true)
    {
        $where = null;

        //批量查询的编号id集合，不存在则查全部
//        if(!empty($params['mids'])){
//            $where['a.mid'] = ['in',$params['mids']];
//        }
        //搜索查询
        if($keyword && $mid){
            $where['a.name|a.mid'] = ['like','%'.$keyword.'%'];
        }elseif($keyword){
            $where['a.name'] = ['like','%'.$keyword.'%'];
        }

        $order = $order?:'';

        $items = VoteItems::getItems($voteId,$typeId,$order,$where);
        return $items;
    }

    public function getComment($voteItemId)
    {
        $comment = Comment::getList($voteItemId);
        if($comment){
            foreach ($comment as &$v){

                $v['create'] = date('m-d H:i',$v['addtime']);
                $v['mobile'] = substr($v['mobile'],0,3).'***'.substr($v['mobile'],-2,2);
                unset($v['ip']);
            }
        }
        return $comment;
    }

    public function addComment($voteItemId,$content,$mobile,$ip)
    {
        $voteItem = $this->getItemById($voteItemId);
        if(!$voteItem)
            return dataReturn(1,'投票信息不存在');

        $vote = $this->getVote($voteItem['vote_id']);
        if(!$vote)
            return dataReturn(1,'投票不存在');

        $comment = [
            'vote_id'=>$vote['id'],
            'vote_item_id'=>$voteItem['id'],
            'mid'=>$voteItem['mid'],
            'mobile'=>$mobile,
            'ip'=>$ip,
            'content'=>$content,
            'addtime'=>time(),
            'modtime'=>time(),
        ];
        switch ($vote['comment_type']){
            case Vote::COMMENT_TYPE_FALSE:
                return dataReturn(1,'该活动不支持评论');
            case Vote::COMMENT_TYPE_BAIDU:
                $back = Baidu::getInstance()->getAccessToken()->verifyText($content);
                if(isset($back['result']) && $back['result']['spam'] == 0){
                    $comment['auto'] = Comment::AUTO_TRUE;
                    $comment['enable'] = Comment::ENABLE_TRUE;
                }else{
                    $comment['auto'] = Comment::AUTO_FALSE;
                    $comment['enable'] = Comment::ENABLE_FALSE;
                }
                break;
            case Vote::COMMENT_TYPE_HAND:
                $comment['enable'] = Comment::ENABLE_FALSE;
                $comment['auto'] = Comment::AUTO_NO_CHECK;
        }

        $res = Comment::insert($comment);
        if(!$res)
            return dataReturn(3,'服务器忙，请稍后再试');

        if($comment['enable'] == Comment::ENABLE_TRUE){
            //清除评论缓存
            $this->clearComment($voteItem['id']);

            return dataReturn(0,'评论成功');
        }

        return dataReturn(2,'评论成功');
    }

    public function formatTime($time)
    {
        $month = date('m',$time);
        $date = date('d',$time);
        $time = date('H:i',$time);
        return $month."月".$date.'日'.$time;
    }

    /**
     * @param $mobile
     * 查看剩余投票数
     */
    public function getLeaveNums(&$vote,$mobile,$ip,$deviceId,$itemId = '')
    {
        $userInfo = [
            //总共可投票数
            'leave_nums' => '',
            //限制单条数据投票数
            'this_leave_nums' => '',
        ];

        //查看该用户是否是白名单规则
        $white = VoteWhite::getWhite($vote['id'],$mobile);

        if($white){
            $vote['nums'] = $white['nums'];
            $vote['per_nums'] = $white['per_nums'];
            $vote['click_nums'] = $white['click_nums'];
        }
        //每天计算投票数
        if($vote['vote_type'] == Vote::VOTE_TYPE_DAY){
            $where['addtime'] = ['>=',strtotime(date('Y-m-d'))];
        }else if($vote['vote_type'] == Vote::VOTE_TYPE_WEEK){
            //每周计算投票数
            //计算每周起始时间，设定的周一为开始
            $week = date("w")==0?7:date('w');
            $thisWeek =mktime(0, 0 , 0,date("m"),date("d")-$week+1,date("Y"));
            $where['addtime'] = ['>=',$thisWeek];
        }
        if(!isset($where)){
            $where = '1=1';
        }

        //账户投票限制
        $a = VoteData::where('vote_id',$vote['id'])
            ->where('mobile',$mobile)
            ->where($where)
            ->where('is_del',VoteData::DEL_FALSE)
            ->field('sum(nums) as total')
            ->find();
        $nums = $a['total']?:0;
        $userInfo['leave_nums'] = $vote['nums'] - $nums;

        //限制IP
        if(!$white && $vote['is_ip']){
            $a = VoteData::where('vote_id',$vote['id'])
                ->where('ip',$ip)
                ->where($where)
                ->where('is_del',VoteData::DEL_FALSE)
                ->field('sum(nums) as total')
                ->find();
            $nums = $a['total']?:0;
            $leave = $vote['ip_nums'] - $nums;
            if($leave < $userInfo['leave_nums']){
                $userInfo['leave_nums'] = $leave;
            }
        }

        //限制设备
        if(!$white && $vote['is_device'] && $deviceId){
            $a = VoteData::where('vote_id',$vote['id'])
                ->where('device_id',$deviceId)
                ->where($where)
                ->where('is_del',VoteData::DEL_FALSE)
                ->field('sum(nums) as total')
                ->find();
            $nums = $a['total']?:0;
            $leave = $vote['device_nums'] - $nums;
            if($leave < $userInfo['leave_nums']){
                $userInfo['leave_nums'] = $leave;
            }
        }


        if($itemId && $vote['per_nums'] >0){
            $a = VoteData::where('vote_id',$vote['id'])
                ->where('vote_item_id',$itemId)
                ->where('mobile',$mobile)
                ->where($where)
                ->where('is_del',VoteData::DEL_FALSE)
                ->field('sum(nums) as total')
                ->find();
            $thisNums = $a['total']?:0;
        }

        //限制所投用户每个比赛投票数不能超出
        if($itemId && $vote['per_nums'] > 0){
            $a = VoteData::where('vote_id',$vote['id'])
                ->where('vote_item_id',$itemId)
                ->where('mobile',$mobile)
                ->where($where)
                ->where('is_del',VoteData::DEL_FALSE)
                ->field('sum(nums) as total')
                ->find();
            $thisNums = $a['total']?:0;
            $userInfo['this_leave_nums'] = $vote['per_nums'] - $thisNums;
        }
        return $userInfo;
    }

    public function getCount($vote_id,$where1,$where2,$max)
    {
        $a = VoteData::where('vote_id',$vote_id)
            ->where($where1)
            ->where($where2)
            ->where('is_del',VoteData::DEL_FALSE)
            ->field('sum(nums) as total')
            ->find();
        $nums = $a['total']?:0;
        $leave = $max - $nums;
        return $leave;
    }

    public function getVoteType($voteId)
    {
        $type =VoteType::getList($voteId);
        return $type;
    }

    public function getTypeById($typeId)
    {
        $type = VoteType::alias('a')
            ->join(Vote::TABLE.' b','b.id=a.vote_id')
            ->where('a.id',$typeId)
            ->where('a.enable',VoteType::ENABLE_YES)
            ->where('b.enable',Vote::ENABLE_TRUE)
            ->field('a.*,b.info')
            ->find();
        return $type;
    }

    public function getItemById($itemId)
    {
        return VoteItems::findOne($itemId);
    }
}